package com.peng.utils.jdkhttp;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.*;
import java.time.Duration;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;


/**
 * Main
 *
 * @author: lupeng6
 * @create: 2021/2/8 11:08
 */
public class Main {

    private static final AtomicLong ATOMIC_LONG = new AtomicLong();

    private HttpClient client;

    @BeforeEach
    public void init() {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                10, 10, 10, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10000 * 100),
                r -> {
                    String threadName = "test-thread-" + ATOMIC_LONG.getAndIncrement();
                    Thread thread = new Thread(r, threadName);
                    return thread;
                },
                new ThreadPoolExecutor.CallerRunsPolicy()
        );

        client = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1)
                .followRedirects(HttpClient.Redirect.NORMAL)
                .connectTimeout(Duration.ofSeconds(5))
                .executor(threadPoolExecutor)
                .build();
    }


    @Test
    public void get() {
        System.out.println(Thread.currentThread().getName());
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://www.baidu.com"))
                .GET()
                .build();

        CompletableFuture<String> responseFuture = client.sendAsync(request, BodyHandlers.ofString())
                .thenApply(HttpResponse::body);
        try {
            String s = responseFuture.get(1, TimeUnit.SECONDS);
            System.out.println(s);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

}
